<template>
  <div>
    <el-dialog
      :append-to-body="true"
      v-if="state.detailDialog"
      :title="state.title"
      v-model="state.detailDialog"
      custom-class="dialogBox"
      :close-on-click-modal="false"
      :modal="false"
      @close="cancel"
    >
      <el-form
        :model="state.formData"
        ref="roleForm"
        label-width="100px"
        class="paddingBox formBox flex_wrap_start_start"
        :rules="rules"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model.trim="state.formData.name"
            maxlength="50"
            @input="(e) => (state.formData.name = validSe(e))"
          />
        </el-form-item>
        <el-form-item :label="$t('code')" prop="code">
          <el-input
            v-model.trim="state.formData.code"
            maxlength="50"
            @input="(e) => (state.formData.code = validSe(e))"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">{{ $t("btn_cancel") }}</el-button>
          <el-button type="primary" @click="_updateRole('roleForm')">{{
            $t("btn_confirm")
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="modifyRole">
import { createRole, updateRole } from "@/api/base.js";

const emit = defineEmits()
const { proxy } = getCurrentInstance();
const props = defineProps({
  tableRow: {
    type: Object,
    defaule: {}
  },
  visible: {
    type: Boolean,
    default: false
  },
});
const state = reactive({
  detailDialog: false,
  title:'',
  formData: {},
});
const rules = reactive({
  code: [
    {
      required: true,
      message: proxy.$t("null_role_code"),
      trigger: "blur",
    },
    { validator: proxy.$validate.validatEn, trigger: "blur" },
  ],
  name: [
    {
      required: true,
      message: proxy.$t("null_role_name"),
      trigger: "blur",
    },
  ],
});

watch(
  () => props.visible,
  (value) => {
    state.detailDialog = value;
  }
);
watch(
  () => props.tableRow,
  (newVal) => {
    state.formData = newVal;
    if (state.formData.id) {
      state.title = "修改角色";
    } else {
      state.title = "新增角色";
    }
  },
  {
    deep: true,
  }
);
function _updateRole(formName) {
  const api = state.formData.id !== undefined ? updateRole : createRole;
  proxy.$refs[formName].validate((valid) => {
    if (valid) {
      api(state.formData).then((resp) => {
        if (resp) {
          state.detailDialog = false;
          emit("callback", true);
        }
      });
    }
  });
}
function cancel() {
  state.detailDialog = false;
  state.formData = {};
  emit("callback", false);
}
</script>

<style scoped></style>
